package com.wejoy.video.middle.station.admin.filter;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import com.wejoy.video.middle.station.admin.util.CurrentUserUtils;
import com.wejoy.video.middle.station.data.domain.system.SysUser;
import com.wejoy.video.middle.station.data.util.user.SysUserLoginUtil;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.ReturnCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

/**
 * @author: admin
 * @time: 2022/9/16 11:20
 */
@Order(1001)
@Configuration
public class LoginPermissionsFilter implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(LoginPermissionsFilter.class);
//    @Value("${domain.admin}")
//    private String adminDomain;

    private static final List<String> IGNORE_URL_LIST = Arrays.asList("/login", "/file/upload", "/common/dict","/files","/excel","/evs/callback");

    private final String RETURN_INFO = JSON.toJSONString(RespJSON.returnCode(ReturnCode.NOT_LOGIN_ERROR));

    private final static String X_TOKEN = "X-Token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 将 options 请求放过
        String method = request.getMethod();
        if ("options".equalsIgnoreCase(method)) {
            return true;
        }
        String uri = request.getRequestURI();
        for (String ignoreUrl : IGNORE_URL_LIST) {
            if (StringUtils.contains(uri, ignoreUrl)) {
                return true;
            }
        }
        String sysUserToken = request.getHeader(X_TOKEN);
        SysUser sysUser = SysUserLoginUtil.getLoginUser(sysUserToken);
        if (null == sysUser) {
            returnNoLogin(response, request);
        }
        SysUserLoginUtil.refreshCache(sysUserToken, sysUser, request);
        return true;

    }

    private void returnNoLogin(HttpServletResponse response, HttpServletRequest request) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(RETURN_INFO);
        } catch (IOException e) {
            logger.error(Throwables.getStackTraceAsString(e));
        } finally {
            writer.close();
        }
    }
}
